<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>计算属性和方法</title>
  <script src="js/vue.min.js"></script>
</head>

<body>
  <div id="app">
  </div>
  <script>
    let app = Vue.createApp({
      template: `
        <div>
          {{now}} - {{count}} - <button @click="updateCount">更新count</button>
          <div>
            说明：计算属性只在相关响应式依赖发生改变时它们才会重新求值，而方法是会重复执行的<br />
            当需要在数据变化时执行异步或开销较大的操作时使用watch侦听器
          </div>
          <div>
          计算属性的getter和setter
            <pre>
              computed: {
                fullName: {
                  // getter
                  get() {
                    return this.firstName + ' ' + this.lastName
                  },
                  // setter
                  set(newValue) {
                    const names = newValue.split(' ')
                    this.firstName = names[0]
                    this.lastName = names[names.length - 1]
                  }
                }
              }
            </pre>
          </div>
        </div>`,
      data() {
        return {
          now: new Date().getTime(),
          count: 1
        }
      },
      computed: {
        countFlag() {
          return this.count > 5
        }
      },
      watch: {
        count(newVal, oldVal) {
          console.log('数据发生变化了')
        }
      },
      methods: {
        updateCount() {
          this.count += 1
        }
      }
    })

    const vm = app.mount('#app')
  </script>
</body>

</html>